/**
 * 
 * @author  phoenics@126.com
 * @version v.0.1
 * @date  2018年3月18日 下午4:21:01 
 * 
 */
package phoenics.upservice.restcontroller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.aliyun.oss.OSSClient;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import phoenics.common.exception.BaseException;
import phoenics.common.exception.ParamsException;
import phoenics.common.util.AliyunOSSClientUtil;
import phoenics.upservice.OSSClientConstants;
import phoenics.upservice.dto.ImageInfo;
import phoenics.upservice.dto.ListPage;
import phoenics.upservice.dto.ListTerm;
import phoenics.upservice.dto.ProjectDTO;
import phoenics.upservice.dto.ProjectPicDTO;
import phoenics.upservice.entity.Project;
import phoenics.upservice.entity.ProjectPic;
import phoenics.upservice.entity.User;
import phoenics.upservice.repository.ProjectPicRepository;
import phoenics.upservice.repository.ProjectRepo;
import phoenics.upservice.service.UserService;

/**
 *
 */
@Api(value = "与项目信息相关API")
@RestController  
@RequestMapping("/info")  
public class ProjectService {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ProjectService.class);
	  private SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd");
	  //private SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy年MM月dd日");
	@Autowired
	ProjectRepo projectRepo;
	@Autowired
	UserService userService;
	@Autowired
	ProjectPicRepository projectPicRepository;
	@Autowired  
    Mapper mapper;  
	
	@ApiOperation(value = "删除图片", notes = "")  
	@PostMapping  (value = "/delImg")
	public void delImg(@RequestBody  ImageInfo  imageInfo) {
		if(imageInfo==null) {
			return;
		}
		if(imageInfo.getId()==null || imageInfo.getId()==0L) {
			return;
		}
		long projectId=Long.valueOf(imageInfo.getId());
		Project project=projectRepo.findOne(projectId);
		if(project==null) {
			throw new ParamsException();
		}
		delImage(imageInfo.getSrcs(),project);
		/*
		if(!imageInfo.getSrc().startsWith("http")) {
			return;
		}
		OSSClient ossClient=AliyunOSSClientUtil.getOSSClient();
		List<ProjectPic> projectPics= projectPicRepository.findByProjectId(projectId);
		String ep="http://"+ossClient.getEndpoint().toString()+"/";
		String imgPath=imageInfo.getSrc().substring(ep.length()+1);
		String f="buildImg/"+project.getId()+"/";
		projectPics.forEach(p->{
			String urlStr=p.getPicUrl();
			if(imgPath.equals(urlStr)) {
				projectPicRepository.delete(p.getId());
				String key=urlStr.substring(f.length()+1);
				AliyunOSSClientUtil.deleteFile(ossClient,f, key);
			}
		});
		*/
	}
	
	private void delImage(String dels,Project project) {
		OSSClient ossClient=AliyunOSSClientUtil.getOSSClient();
		List<ProjectPic> projectPics= projectPicRepository.findByProjectId(project.getId());
		//String ep="http://"+ossClient.getEndpoint().toString()+"/";
		//String imgPath=imageInfo.getSrc().substring(ep.length()+1);
		String f="buildImg/"+project.getId()+"/";
		projectPics.forEach(p->{
			String urlStr=p.getPicUrl();
			if(dels.indexOf(urlStr)>0) {
				projectPicRepository.delete(p.getId());
				String key=urlStr.substring(f.length());
				//logger.info("delImage=key====={}",key);
				//logger.info("delImage=f====={}",key);
				AliyunOSSClientUtil.deleteFile(ossClient,f, key);
			}
		});
	}
	@ApiOperation(value = "更新图片", notes = "")  
	@PostMapping  (value = "/updateImg")
	public void uploadImage(HttpServletRequest request) {
		//MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//MultipartHttpServletRequest mRequest = resolver.resolveMultipart(request);
		logger.info("======uploadImage==========");
		MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
		String pid=mRequest.getParameter("pid");
		logger.info("======uploadImage===pid======={}",pid);
		long projectId=Long.valueOf(pid);
		Project project=projectRepo.findOne(projectId);
	
		if(project==null) {
			throw new ParamsException();
		}
		logger.info("======uploadImage===project===={}===",project.getId());
		Map<String, MultipartFile> maps=mRequest.getFileMap();
		OSSClient ossClient=AliyunOSSClientUtil.getOSSClient();
		logger.info("=====ossClient=============");
		//User userE=userService.takePrincipal();
		maps.keySet().forEach(key->{
			 MultipartFile file =maps.get(key);
			 saveImage(ossClient,file,project);
		});
		String delStr=(String)mRequest.getParameter("delStr");
		delImage(delStr,project);
	}
	
	private void saveImage(OSSClient ossClient,MultipartFile file,Project project) {
		 String f="buildImg/"+project.getId()+"/";
		 logger.info(f);
		 logger.info(file.getName());
		 String path=AliyunOSSClientUtil.uploadObject2OSS(ossClient, file, f);
		 ProjectPic projectPic= new ProjectPic();
		 projectPic.setPicUrl(path);
		 projectPic.setProject(project);
		 projectPicRepository.save(projectPic);
	}
	
	private Page<ListPage> allList( Integer up,Integer page,Integer size,ListTerm terms) {
		Sort sort = new Sort(Direction.DESC, "id");
		Pageable pageable = new PageRequest(page, size, sort);
		Page<Project> lists=null;
		if(up!=0) {
			pageable = new PageRequest(0, Integer.MAX_VALUE, sort);
			if(StringUtils.isBlank(terms.getAreaCode()) && StringUtils.isBlank(terms.getClassifyCode())) {
				lists=projectRepo.findAllDown(terms.getMin(),pageable);
			}else if(StringUtils.isNotBlank(terms.getAreaCode()) && StringUtils.isBlank(terms.getClassifyCode())) {
				lists=projectRepo.findByProjectAreaDown(terms.getAreaCode(),terms.getMin(), pageable);
			}else if(StringUtils.isBlank(terms.getAreaCode())  && StringUtils.isNotBlank(terms.getClassifyCode())) {
				lists=projectRepo.findByProjectCategoryDown(terms.getClassifyCode(),terms.getMin(), pageable);
			}else {
				lists=projectRepo.projectPageDataDown(terms.getClassifyCode(), terms.getAreaCode(),terms.getMin(), pageable);
			}
			if(lists==null) {
				throw new BaseException(-1,"查询错误");
			}
		}else {
			if(terms.getMax()==0) {
				terms.setMax(Long.MAX_VALUE);
			}
			if(StringUtils.isBlank(terms.getAreaCode()) && StringUtils.isBlank(terms.getClassifyCode())) {
				lists=projectRepo.findAllUp(terms.getMax(),pageable);
			}else if(StringUtils.isNotBlank(terms.getAreaCode()) && StringUtils.isBlank(terms.getClassifyCode())) {
				lists=projectRepo.findByProjectAreaUp(terms.getAreaCode(),terms.getMax(), pageable);
			}else if(StringUtils.isBlank(terms.getAreaCode())  && StringUtils.isNotBlank(terms.getClassifyCode())) {
				lists=projectRepo.findByProjectCategoryUp(terms.getClassifyCode(),terms.getMax(), pageable);
			}else {
				lists=projectRepo.projectPageDataUp(terms.getClassifyCode(), terms.getAreaCode(),terms.getMax(), pageable);
			}
			if(lists==null) {
				throw new BaseException(-1,"查询错误");
			}
		}
		List<ListPage> content= lists.getContent().stream().map(this::ListPageMapper).collect(Collectors.toList());
		return new PageImpl<>(content,pageable,lists.getTotalElements());
	}
	@ApiOperation(value = "自己发布的信息", notes = "")  
	@GetMapping  (value = "/mylist")
	public List<ListPage> projectMeList(
			) {
		User userE=userService.takePrincipal();
		List<Project> ups=projectRepo.findFollows(userE.getId());
		 return Optional.ofNullable(ups).orElseGet(Collections::emptyList).stream().map(u->ListPageMapper(u)
				).collect(Collectors.toList());
	}
	@ApiOperation(value = "获取关注详情", notes = "")  
	@GetMapping  (value = "/mylist/{id}")
	public ProjectDTO projectMeListDetail(@PathVariable("id") Long id) {
		User userE=userService.takePrincipal();
		Optional<Project> ups=projectRepo.findFollow(userE.getId(),id);
		return ups.map(u->pDetails(u)).map(p->hiddenDetails(p)).get();
	}
	
	private ProjectDTO hiddenDetails(ProjectDTO projectDTO) {
		
		projectDTO.setProjectAddress("***");
		projectDTO.setProjectDuties1Tel("***");
		projectDTO.setProjectDuties2Tel("***");
		projectDTO.setProjectDuties3Tel("***");
		return projectDTO;
	}
	
	@ApiOperation(value = "自己发布的信息page", notes = "")  
	@PostMapping  (value = "/plist")
	public Page<ListPage> projectMeList(
			@RequestParam(value = "up", defaultValue = "0") Integer up,
			@RequestParam(value = "page", defaultValue = "0") Integer page,
			@RequestParam(value = "size", defaultValue = "10") Integer size,
			@RequestBody ListTerm terms){  
		Sort sort = new Sort(Direction.DESC, "id");
		Pageable pageable = new PageRequest(page, size, sort);
		Page<Project> lists=null;
		
		if(up!=0) {
			pageable = new PageRequest(0, Integer.MAX_VALUE, sort);
			lists=projectRepo.findAllDown(terms.getMin(),userService.takePrincipal().getId(),pageable);
			if(lists==null) {
				throw new BaseException(-1,"查询错误");
			}
		}else {
			if(terms.getMax()==0) {
				terms.setMax(Long.MAX_VALUE);
			}
			lists=projectRepo.findAllUp(terms.getMax(),userService.takePrincipal().getId(),pageable);
			if(lists==null) {
				throw new BaseException(-1,"查询错误");
			}
		}
		List<ListPage> content= lists.getContent().stream().map(this::ListPageMapper).collect(Collectors.toList());
		 return new PageImpl<>(content,pageable,lists.getTotalElements());
	}
	@ApiOperation(value = "通过条件取得列表", notes = "")  
	@PostMapping  (value = "/list")
	public  Page<ListPage> projectList(
			@RequestParam(value = "up", defaultValue = "0") Integer up,
			@RequestParam(value = "page", defaultValue = "0") Integer page,
			@RequestParam(value = "size", defaultValue = "10") Integer size,
			@RequestBody ListTerm terms){  
		return this.allList(up,page,size,terms);
	
	}
	private ListPage ListPageMapper(Project project) {
		logger.info(project.getProjectName());
		ListPage lp=new ListPage();
		BeanUtils.copyProperties(project,lp);
		lp.setOpenDate(myFmt.format(project.getOpenDate()));
		lp.getPicUr().clear();
		project.getProjectPics().forEach(p-> lp.getPicUr().add(OSSClientConstants.HTTPPATH+p.getPicUrl()));
		return lp;
	}
	private Long midifyData(ProjectDTO projectDTO,Project project) throws ParseException{  
		BeanUtils.copyProperties(projectDTO,project);
		project.setOpenDate(myFmt.parse(projectDTO.getOpenDate()));
		project.setUser(userService.takePrincipal());
		project.setProjectPics(null);
		Project s=projectRepo.save(project);
		return s.getId();
	}
	@ApiOperation(value = "发布一条工程信息", notes = "")  
	@PostMapping  (value = "/add")
	public Long projectPublic(@RequestBody ProjectDTO projectDTO) throws ParseException{  
		return midifyData(projectDTO,new Project());
	}
	@ApiOperation(value = "更改一条工程信息", notes = "")  
	@PutMapping  (value = "/update/{id}")
	public Long projectPublic(@RequestBody ProjectDTO projectDTO,@PathVariable("id") Long id) throws ParseException{  
		Project project=projectRepo.findProjectByIdAndUserId(id,userService.takePrincipal().getId());
		 return midifyData(projectDTO,project);
	}
	@ApiOperation(value = "工程详细信息", notes = "")  
	@GetMapping  (value = "/list/{id}")
	public ProjectDTO projectDetails(@PathVariable("id") Long id) {
		Project project=projectRepo.findProjectByid(id);
		ProjectDTO projectDTO=pDetails(project);
		//ProjectDTO projectDTO=new ProjectDTO();
		//long uid=userService.takePrincipal().getId();
		User user=project.getUser();
		if(user==null) {
			return null;
		}
		
		projectDTO.setProjectAddress("***");
		projectDTO.setProjectDuties1Tel("133***");
		projectDTO.setProjectDuties2Tel("133***");
		projectDTO.setProjectDuties3Tel("133***");
		return projectDTO;
	}
	
	
	@ApiOperation(value = "增加关注", notes = "")  
	@GetMapping  (value = "/list/{id}/addfollow")
	public boolean projectAddFollow(@PathVariable("id") Long id) {
		Project project=projectRepo.findOne(id);
		project.getUsers().add(userService.takePrincipal());
		if(projectRepo.save(project)!=null) {
			return true;
		}
		return false;
	}
	
	@ApiOperation(value = "取消关注", notes = "")  
	@GetMapping  (value = "/list/{id}/delfollow")
	public boolean projectDelFollow(@PathVariable("id") Long id) {
		Project project=projectRepo.findOne(id);
		User userE=userService.takePrincipal();
		List<User> dels=project.getUsers().stream().filter(u->u.getId().equals(userE.getId())).collect(Collectors.toList());
		project.getUsers().removeAll(dels);
		if(projectRepo.save(project)!=null) {
			return  true;
		}
		return false;
	}

	@ApiOperation(value = "获取关注page", notes = "")  
	@GetMapping  (value = "/followpage")
	public Page<ListPage> projecFollows(
			@RequestParam(value = "up", defaultValue = "0") Integer up,
			@RequestParam(value = "page", defaultValue = "0") Integer page,
			@RequestParam(value = "size", defaultValue = "10") Integer size
			) {
		Sort sort = new Sort(Direction.DESC, "id");
		Pageable pageable = new PageRequest(page, size, sort);
		if(up!=0) {
			pageable = new PageRequest(0, Integer.MAX_VALUE, sort);
		}
		User userE=userService.takePrincipal();
		Page<Project> lists= projectRepo.findFollows(userE.getId(),  pageable);
		List<ListPage> content= lists.getContent().stream().map(this::ListPageMapper).collect(Collectors.toList());
		return new PageImpl<>(content,pageable,lists.getTotalElements());
	}
	
	private ProjectDTO pDetails(Project project) {
		User userE=userService.takePrincipal();
		//ProjectDTO projectDTO=new ProjectDTO();
		//project.setUser(null);
		//BeanUtils.copyProperties(project,projectDTO);
		ProjectDTO projectDTO=mapper.map(project, ProjectDTO.class);
		projectDTO.setOpenDate(myFmt.format(project.getOpenDate()));
		//BeanUtils.copyProperties(project,projectDTO);
		//projectDTO.setOpenDate(myFmt2.format(project.getOpenDate()));
		//logger.info(projectDTO.getOpenDate()+"======================");
		//Optional<ProjectDTO> parentVal = Optional.ofNullable(projectDTO);
		projectDTO.getProjectPics().clear();
		List<ProjectPicDTO> pdto=project.getProjectPics().stream().map(p->{
			ProjectPicDTO dto=new ProjectPicDTO();
			dto.setDetail(p.getDetail());
			dto.setPicUrl(OSSClientConstants.HTTPPATH+p.getPicUrl());
			return dto;
		}).collect(Collectors.toList());
		projectDTO.getProjectPics().addAll(pdto);
		project.getUsers().stream().filter(u->u.getId().equals(userE.getId())).findFirst().ifPresent(u->projectDTO.setConcern(true));
		projectDTO.setFollow(
				projectRepo.findFollow(userE.getId(), project.getId()).map(u->true).orElse(false));
		//projectDTO.setProjectPics(pdto);
		return projectDTO;
	}
}
